<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Models\Movie;
use App\Models\Category;
use App\Models\Star;
use Illuminate\Pagination\LengthAwarePaginator;
use App\Transformers\MovieTransformer;
use App\SearchBuilders\MovieSearchBuilder;
class MoviesController extends Controller
{

    public function index(Movie $movie, Request $request)
    {
        $category = $request->category;
        $watched_id = $request->input('watched_id', 0);
        $query = $movie->newUpdated();
        if ($category > 0) {
            $query->whereHas('categories', function($q) use ($category) {
                $q->where('category_id', $category);
            });
            $category = Category::find($category);
        }
        if ($watched_id) {
            $query->where('category_id', 100);
        }
        if ($actor_id = $request->actor_id) {
            $query->whereHas('actors', function ($q) use ($actor_id) {
                $q->where('actor_id', $actor_id);
            });
        }

        if ($director_id = $request->director_id) {
            $query->whereHas('directors', function ($q) use ($director_id) {
                $q->where('director_id', $director_id);
            });
        }

        if ($area = $request->area) {
            $query->where('area', $area);
        }

        $movies = $query->paginate(10);
        if ($this->user()) {
            $watchs = $this->user()->watchStatusWithMovies($movies->pluck('id'));
        } else {
            $watchs = null;
        }

        return $this->response->paginator($movies, new MovieTransformer($watchs))
                                ->addMeta('category', $category);
    }
    public function search(Request $request)
    {
        $page    = $request->input('page', 1);
        $perPage = $request->input('limit', 10);

        $builder = (new MovieSearchBuilder());
        if ($filter_category = Category::where('name', '情色')->first()) {
            $builder->onSale($filter_category);
        }

        $builder->paginate($perPage, $page);

        if ($search = $request->input('search', '')) {
            $keywords = array_filter(explode(' ', $search));
            // 调用查询构造器的关键词筛选
            $builder->keywords($keywords);
        }

        if ($order = $request->input('order', '')) {
            if (preg_match('/^(.+)_(asc|desc)$/', $order, $m)) {
                if (in_array($m[1], ['score', 'year'])) {
                    // 调用查询构造器的排序
                    $builder->orderBy($m[1], $m[2]);
                }
            }
        }
        if ($star = $request->input('star', '')) {
            $builder->star($star);
        }

        if ($year = $request->input('year', 0)) {
            $builder->year($year);
        }

        if ($area = $request->input('area', '')) {
            $builder->area($area);
        }
        if ($request->input('category_id') && $category = Category::find($request->input('category_id'))) {
            // 调用查询构造器的类目筛选
            $builder->category($category);
        }
        if ($request->input('actor_id') && $star = Star::find($request->input('actor_id'))) {
            // 调用查询构造器的演员筛选
            $builder->actor($star);
        }
        if ($request->input('director_id') && $star = Star::find($request->input('director_id'))) {
            // 调用查询构造器的导演筛选
            $builder->director($star);
        }
        if ($request->input('author_id') && $star = Star::find($request->input('author_id'))) {
            // 调用查询构造器的编剧筛选
            $builder->author($star);
        }
        // $builder->aggregateProperties();
        $result = app('es')->search($builder->getParams());
        $movieIds = collect($result['hits']['hits'])->pluck('_id')->all();
        $movies = Movie::query()
            ->whereIn('id', $movieIds)
            ->orderByRaw(sprintf("FIND_IN_SET(id, '%s')", join(',', $movieIds)))
            ->get();
        // 查询当前登录用户 和 电影的关系
        if ($this->user()) {
            $watchs = $this->user()->watchStatusWithMovies($movieIds);
        } else {
            $watchs = null;
        }


        $pager = new LengthAwarePaginator($movies, $result['hits']['total'], $perPage, $page, [
            'path' => '', // 手动构建分页的 url
        ]);
        /*
        $properties = [];
        // 如果返回结果里有 aggregations 字段，说明做了分面搜索
        if (isset($result['aggregations']) && (empty($area) || $area === '全部')) {
            // 使用 collect 函数将返回值转为集合
            $properties = collect($result['aggregations']['properties']['properties']['buckets'])
                ->map(function ($bucket) {
                    // 通过 map 方法取出我们需要的字段
                    return $bucket['key'];
                })->toArray();
            sort($properties);
        }
        */
        return $this->response->paginator($pager, new MovieTransformer($watchs)); // ->addMeta('areas', $properties);
    }
    public function show(Movie $movie, Request $request)
    {
        if ($this->user()) {
            $watchs = $this->user()->watchStatusWithMovies([$movie->id]);
        } else {
            $watchs = null;
        }
        return $this->response->item($movie, new MovieTransformer($watchs));
    }
}
